﻿using System.Collections.Generic;
using System.Linq;
using System.Web;
using Easy.Extend;
using Easy.Web.CMS;
using Easy.Web.CMS.Page;
using Easy.Web.CMS.Widget;
using Microsoft.Practices.ServiceLocation;
using System.Web.Mvc;
using Easy.CMS.List.Models;
using Easy.MetaData;
using System;
using Easy.Data;
using Easy.CMS.List.ViewModel;
using System.Net.Http;
using Newtonsoft.Json;
using Easy.Web.CMS.Helper;
using System.Net.Http.Headers;
using Newtonsoft.Json.Linq;
using System.Text;
using System.Data;
using Easy.Web.CMS.Data;

namespace Easy.CMS.List.Service
{
    public class ListDetailWidgetService : WidgetService<ListDetailWidget>
    {
        public override WidgetPart Display(WidgetBase widget, ControllerContext controllerContext)
        {
            string detailId = controllerContext.RouteData.GetListID();

            var currentWidget = widget as ListDetailWidget;

            var viewModel = new ListDetailViewModel()
            {
                Widget = currentWidget
            };

            string headField = currentWidget.Head;
            string contentField = currentWidget.Content;
            string formCode = currentWidget.FormCode;

            if (!string.IsNullOrEmpty(formCode) && !string.IsNullOrEmpty(detailId))
            {
                StringBuilder select = new StringBuilder(string.Format("select [Id], [{0}], [{1}] ", viewModel.Field_UpdateDate, viewModel.Field_CreateBy));
                if (!string.IsNullOrEmpty(headField))
                {
                    select.AppendFormat(",{0} ", headField);
                }
                if (!string.IsNullOrEmpty(contentField))
                {
                    select.AppendFormat(",{0}", contentField);
                }
                select.AppendFormat(" from {0} where Id = '{1}' ", formCode, detailId);
                DataSet ds = YunPanDbHelper.Query(select.ToString());
                if (ds.HasData())
                {
                    viewModel.JsonResult = ds.GetJsonString();
                }
            }
            return widget.ToWidgetPart(viewModel);
        }
    }
}